import Vue from "vue";
import Vuex from "vuex"; // 导入vuex

Vue.use(Vuex); // 实际执行 Vuex.install(Vue)

import { SET_COUNT, SAY, ADD, SET_TITLE } from "./mutations.js";

//全局对象
const store = new Vuex.Store({
  //data 状态
  // state:{}
  state() {
    return {
      title: "hello vuex",
      firstName: "li",
      lastName: "jack",
      num1: 100,
      num2: 200,
      count: 20,
    };
  },
  // computed
  getters: {
    g1() {
      return 100;
    },
    g2() {
      return 200;
    },
    fullName(state, getters) {
      return `${state.lastName} ${state.firstName} ${getters.g1}`;
    },
  },
  // methods 方法
  mutations: {
    SET_TITLE: (state, str = "") => {
      // setTimeout(() => {
      state.title = str;
      // }, 2000);
    },
    [SET_COUNT](state, num = 1) {
      // setTimeout(() => {
      state.count += num;
      // }, 2000);
    },
    [SAY](state) {
      console.log(state.title);
    },
    [ADD](state, arg) {
      console.log(state.num1 + state.num2 + arg);
    },
  },

  actions: {
    add(store, data) {
      // setTimeout(()=>{
      // console.log(store.state.title);
      // console.log(store.getters.fullName);
      // store.commit(SET_TITLE,'hahaha');
      // },3000)

      console.log(data + 1000);

      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     resolve(10 + data);
      //     // reject(new Error("..."));
      //   }, 3000);
      // });

      // return 10+data;
    },
  },
  // children
  modules: {
    a: {
      namespaced: true,
      state: () => ({
        title: "hello a",
      }),
      getters: {
        ga1: () => 100,
        ga2: () => 200,
      },
      mutations: {
        SET_TITLE: (state, value = "") => (state.title = value),
      },
      actions: {
        add(store, obj) {
          console.log(obj.a + obj.b);
        },
      },
      modules: {
        a1: {
          namespaced: true,
          state: () => ({
            title: "hello a1",
            num: 100,
          }),
          getters: {
            ga3: (state, getters, rootState) => 300 + rootState.num2,
            ga4: () => 400,
          },
          mutations: {
            SET_TITLE: (state, value = "") => (state.title = value),
          },
          actions: {
            add(store, obj) {
              console.log(
                obj.a +
                  obj.b +
                  store.state.num +
                  store.getters.ga3 +
                  store.rootState.num1 +
                  store.rootGetters.g1 +
                  store.rootGetters.g2
              );
            },
          },
        },
        a2: {},
      },
    },
    b: {
      state: () => ({}),
    },
    c: {
      actions: {},
    },
  },
});

export default store;
